package com.brian.doorchain.fliter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-27 23
 **/
@WebFilter(filterName = "souceFliter", urlPatterns = "/webjars/*")
public class SouceFliter implements Filter {
    @Value("${domain.name}")
    private String domainName;

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String referer = req.getHeader("Referer");
        if (StringUtils.isEmpty(referer)) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("知识保护，申请访问请联系: 1092249319@qq.com");
           // request.getRequestDispatcher("/imgs/error.png").forward(request, response);
            return;
        }
        String domain = getDomain(referer);
        if (!domain.equals(domainName)) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("知识保护，申请访问请联系: 1092249319@qq.com");
           // request.getRequestDispatcher("/imgs/error.png").forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }

    /**
     * 获取url对应的域名
     *
     * @param url
     * @return
     */
    public String getDomain(String url) {
        String result = "";
        int j = 0, startIndex = 0, endIndex = 0;
        for (int i = 0; i < url.length(); i++) {
            if (url.charAt(i) == '/') {
                j++;
                if (j == 2)
                    startIndex = i;
                else if (j == 3)
                    endIndex = i;
            }

        }
        result = url.substring(startIndex + 1, endIndex);
        return result;
    }

    public void destroy() {

    }

}
